<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
    <div class="g-drawer-list-container">
      <div class="g-drawer-progress-container">
        <TitleSecondary title="审批流程图" />
        <ProgressStaus />
      </div>
      <ProgressTransverse
        :node-list="detail.nodeList"
        :name-list="detail.nameList"
      />
      <TitleSecondary title="基本信息" />
      <FormBasicInfoList :form="form" :plan-type="planType" />
      <TitleSecondary title="销售责任人" />
      <TableSaleList
        :data-source="detail.planSales"
        style="margin-bottom: 20px"
      />
      <TitleSecondary :title="`${PLAN_TYPE[planType]}计划明细`" />

      <p-tabs
        :default-active-key="hasEdit ? '2' : '1'"
        type="card"
        class="g-drawer-poros-tabs"
        @change="handleTabChange"
      >
        <p-tab-pane key="1" :tab="`初版${PLAN_TYPE[planType]}目标`">
          <TablePlanDetail
            ref="table-detail"
            :data-source="planDetailList"
            :is-edit="false"
            :plan-sales="detail.planSales"
            :detail-copy="detailStartCopy"
            :plan-id="planId"
            :plan-type="planType"
            :hide-keys="['selection']"
            :local-key="`${PLAN_TYPE[planType]}-submit-audit`"
            :buttons="[
              {
                key: 'export',
                label: '导出',
              },
              {
                key: 'show',
                label: '显示字段',
              },
              {
                key: 'screenfull',
                label: '全屏显示',
              },
            ]"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            @checked="handleTableCheckedChange"
          />
        </p-tab-pane>
        <p-tab-pane
          v-if="hasEdit"
          key="2"
          :tab="`终版${PLAN_TYPE[planType]}目标`"
        >
          <TablePlanDetail
            ref="table-detail-end"
            :data-source="endPlanDetailList"
            :plan-sales="detail.planSales"
            :plan-type="planType"
            :plan-id="planId"
            :plan-sales-id="detail.planSalesId"
            :local-key="`${PLAN_TYPE[planType]}-submit-audit-end`"
            template-name="终版"
            :hide-keys="['selection', 'relationId']"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            :buttons="buttons"
            :default-show="[]"
            :default-fixed="[]"
            @getstart="handleGetStart"
          />
        </p-tab-pane>
      </p-tabs>

      <TitleSecondary v-if="hasEdit" title="提交信息" />
      <InfoSubmit v-if="hasEdit" ref="approval" />
      <TitleSecondary
        title="操作日志"
        :icon="iconStaus"
        @change="handleChangeIcon"
      />
      <ProgressPortrait
        v-show="isShowProgressPortrait"
        :operation-log="operationLogInformation"
      />
      <BottomLine />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
    <DialogTransfer
      :visible.sync="visibleTransfer"
      :plan-id="planId"
      @change="onClose"
    />
  </p-drawer>
</template>

<script>
import FormBasicInfoList from '@/components/task/FormBasicInfoList.vue';
import TableSaleList from '@/components/task/TableSaleList.vue';
import ProgressTransverse from '@/components/task/ProgressTransverse.vue';
import ProgressPortrait from '@/components/task/ProgressPortrait.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';
import TablePlanDetail from '@/components/task/TablePlanDetail.vue';
import DialogTransfer from '@/components/dialog/DialogTransfer.vue';

import InfoSubmit from '@/components/task/InfoSubmit.vue';

import { getOperationLog, postFinalConfirmation } from '@/api/plan';
import DrawerMixin from './mixin';

const buttons = [
  {
    key: 'add',
    type: 'primary',
    label: '新增',
    icon: 'plus',
  },
  {
    key: 'getstart',
    label: '引用初版',
  },
  {
    key: 'delete',
    label: '删除',
  },
  {
    key: 'insert',
    label: '导入',
  },
  {
    key: 'download',
    label: '下载模板',
  },
  {
    key: 'relation',
    label: '关联BP关系ID',
  },
  {
    key: 'show',
    label: '显示字段',
  },
];

import { isEmpty } from '@/utils/is';

const requireKey = [
  'planSalesId',
  'customerCode',
  'modelName',
  'modelNumber',
  'application',
  'appearance',
  'modelCutRate',
  'price',
  'quantity',
  'factoryCode',
];

export default {
  components: {
    FormBasicInfoList,
    TablePlanDetail,
    TableSaleList,
    ProgressTransverse,
    ProgressPortrait,
    ProgressStaus,
    InfoSubmit,
    DialogTransfer,
  },

  mixins: [DrawerMixin],

  props: {},
  data() {
    this.buttons = buttons;
    return {
      operationLogInformation: [], //操作日志请求返回的信息
      iconStaus: 'down', //icon图片up、down的切换
      planDetailList: [],
      endPlanDetailList: [],
      visibleTransfer: false,
    };
  },
  computed: {
    saleGroupOptions() {
      return this.detail.planSales.reduce((pre, cur) => {
        pre[cur.salesGroupName] = cur.id;
        return pre;
      }, {});
    },
    isShowProgressPortrait() {
      return this.iconStaus === 'up';
    },
    form() {
      return this.detail.plan || {};
    },
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'save',
          label: '保存',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },

  methods: {
    handleTabChange() {},
    async handleChangeIcon(icon) {
      this.iconStaus = icon === 'down' ? 'up' : 'down';
      if (this.operationLogInformation.length === 0) {
        let res = await getOperationLog({
          planNumber: this.planId,
        });
        this.operationLogInformation = res.data.data;
      }
    },
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    async submitData(operating) {
      const endPlanDetailList = this.endPlanDetailList.map((item) => {
        const price = Object.keys(item).reduce((pre, cur) => {
          if (cur.startsWith('pricemonth')) {
            const month = cur.split('_')[1];
            month !== 'total' && (pre[month] = item[cur]);
          }
          return pre;
        }, {});
        const quantity = Object.keys(item).reduce((pre, cur) => {
          if (cur.startsWith('quantitymonth')) {
            const month = cur.split('_')[1];
            month !== 'total' && (pre[month] = item[cur]);
          }
          return pre;
        }, {});
        const temp = Object.keys(item).reduce((pre, cur) => {
          if (cur.includes('month_')) {
            pre[cur] = item[cur];
          }
          return pre;
        }, {});

        const salesGroupName = this.detail.planSales.find(
          (el) => el.id === item.planSalesId
        )?.salesGroupName;
        return {
          relationId: item.relationId,
          appearance: item.appearance,
          factoryCode: item.factoryCode,
          materialCode: item.materialCode,
          bpRelationId: item.bpRelationId,
          category: item.category,
          application: item.application,
          customerCode: item.customerCode?.key,
          customerName: item.customerCode?.label,
          innerItem: item.innerItem,
          item: item.item,
          manufactureArea: item.manufactureArea,
          modelCutRate: item.modelCutRate,
          modelCode: item.modelName?.key,
          modelName: item.modelName?.label,
          modelNumber: item.modelNumber?.key,
          modelInfoName: item.modelNumber?.label,
          remark: item.remark,
          price: JSON.stringify(price),
          quantity: JSON.stringify(quantity),
          temp: JSON.stringify(temp),
          salesGroupName: salesGroupName,
          planSalesId: item.planSalesId,
        };
      });
      const form = this.$refs.approval?.form || {};
      if (operating === 0) {
        const isValid = this.checkData(endPlanDetailList);
        if (!isValid) return new Promise(() => {});

        if (!form.approveOpinion && operating === 0) {
          this.$message.error('请填写审批意见！');
          return new Promise(() => {});
        }
      }
      return await postFinalConfirmation({
        planId: this.planId,
        // planSalesId: this.detail.planSales[0].id,
        // responsibleId: this.detail.planSales[0].responsibleId,
        ...form,
        operating,
        endPlanDetailList,
      });
    },
    checkData(list) {
      if (!list.length) {
        this.$message.error('请先填写表格内容！');
        return false;
      }
      const index = list.findIndex((item) => {
        const price = JSON.parse(item.price);
        const isPrice = Object.keys(price).some((key) => isEmpty(price[key]));
        const quantity = JSON.parse(item.quantity);
        const isQuantity = Object.keys(quantity).some((key) =>
          isEmpty(quantity[key])
        );
        return (
          isPrice || isQuantity || requireKey.some((key) => isEmpty(item[key]))
        );
      });
      if (index > -1) {
        this.$message.error('计划明细表数据未填写完整，请补充！');
        return false;
      }
      return true;
    },
    closeCallback() {
      this.onClose();
    },
    async submitCallback() {
      await this.submitData(0);
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    async saveCallback() {
      await this.submitData(1);
      this.$message.success('保存成功！');
      this.closeCallback();
    },
    transferCallback() {
      this.visibleTransfer = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    handleGetStart() {
      const data = JSON.parse(JSON.stringify(this.planDetailList)).map(
        (item) => ({ ...item, relationId: undefined })
      );
      if (this.endPlanDetailList.length) {
        this.$confirm('引用后会覆盖手动添加的数据，确定是否引用？')
          .then((vaild) => {
            if (vaild) {
              this.endPlanDetailList = data;
              this.$nextTick(() => {
                this.$refs['table-detail-end'].onSearch();
              });
            }
          })
          .catch(() => {});
      } else {
        this.endPlanDetailList = data;
        this.$nextTick(() => {
          this.$refs['table-detail-end'].onSearch();
        });
      }
    },
  },
};
</script>

